package com.idbk.chargestation.util;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * bitmap相关的处理
 * @author lupc
 *
 */
public class BitmapHelper {

	public static String getRealPathFromURI(Context context,Uri contentUri) {
		String res = null;
		String[] proj = { MediaStore.Images.Media.DATA };
		Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
		if (cursor != null) {
			if(cursor.moveToFirst()){
				int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
				res = cursor.getString(column_index);
			}
			cursor.close();
		}
		return res;
	}

	public static File getFileFromUri(Context context,Uri uri){
		String path = getRealPathFromURI(context,uri);
		File file = new File(path);		
		return file;
	}

	public static int getFileSize(File file){
		int size = 0;
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(file);
			size = fis.available();
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			try {
				if(fis != null){
					fis.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}			
		}
		return size;
	}

	public static boolean compressBitmap(File input,File output){
		//先读出图片的实际大小
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(input.getPath(), options);
		int height = options.outHeight;
		int width = options.outWidth; 

		//计算压缩比例
		int inSampleSize = 1;
		int reqHeight = 800;
		int reqWidth = 480;
		if (height > reqHeight || width > reqWidth) {
			final int heightRatio = Math.round((float) height/ (float) reqHeight);
			final int widthRatio = Math.round((float) width / (float) reqWidth);            
			inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
		}

		//压缩图片大小
		options.inSampleSize = inSampleSize;
		options.inJustDecodeBounds = false;
		Bitmap bmp = BitmapFactory.decodeFile(input.getPath(), options);

		//压缩图片质量
		try {
			FileOutputStream fos = new FileOutputStream(output.getPath());               
			bmp.compress(Bitmap.CompressFormat.JPEG, 60, fos);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} 
		
		//
		//bmp.recycle();
		
	}

}
